package com.kmis.common.security;

import cn.hutool.core.util.StrUtil;
import com.kmis.common.constant.JwtConstant;
import com.kmis.services.IUserService;
import com.kmis.utils.JwtUtil;
import com.kmis.vo.UserVo;
import com.kmis.web.CheckResult;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author moc
 * jwt认证流程
 */
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    private IUserService service;


    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    /**
     * 放行白名单
     */
    private static final String[] URL_WHITELIST ={
            "/login",
            "/logout",
            "/image/**",
            "/files/**",
            "/file/**"
    } ;


    /**
     * 过滤器
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        //如果在白名单里或者token为空则放行
        if(StrUtil.isEmpty(token)||new ArrayList<String>(Arrays.asList(URL_WHITELIST)).contains(request.getRequestURI())){
            chain.doFilter(request,response);
            return;
        }
        //检查token状态码输出相应的错误状态
        CheckResult checkResult = JwtUtil.validateJWT(token);
        if(!checkResult.isSuccess()){
            switch (checkResult.getErrorCode()) {
                case JwtConstant.JWT_ERROR_NULL:
                    throw new JwtException("Token不存在");
                case JwtConstant.JWT_ERROR_FAIL:
                    throw new JwtException("Token验证不通过");
                case JwtConstant.JWT_ERROR_EXPIRE:
                    throw new
                            JwtException("Token过期");
            }
        }
        Claims claims = JwtUtil.parseJwt(token);
        String username = claims.getSubject();
        UserVo user = service.getByUserName(username);
        //对用户名和密码进行认证的一个类
        UsernamePasswordAuthenticationToken up = new UsernamePasswordAuthenticationToken(username,null,null);
        SecurityContextHolder.getContext().setAuthentication(up);
        chain.doFilter(request,response);
    }
}
